import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useMessageStore = defineStore('message', () => {
  const messages = ref([])
  const currentMessage = ref(null)
  
  // 计算属性
  const unreadCount = computed(() => {
    return messages.value.filter(msg => !msg.isRead).length
  })
  
  const sortedMessages = computed(() => {
    return [...messages.value].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
  })
  
  // 添加消息
  const addMessage = (message) => {
    const newMessage = {
      id: message.id || Date.now().toString(),
      title: message.title || '新消息',
      content: message.content || '',
      summary: message.summary || message.content?.substring(0, 100) + '...',
      source: message.source || '系统',
      timestamp: message.timestamp || new Date().toISOString(),
      isRead: false,
      ...message
    }
    
    // 检查是否已存在
    const existingIndex = messages.value.findIndex(msg => msg.id === newMessage.id)
    if (existingIndex >= 0) {
      messages.value[existingIndex] = newMessage
    } else {
      messages.value.unshift(newMessage)
    }
    
    // 保存到本地存储
    saveToLocal()
    
    // 更新角标
    updateBadge()
  }
  
  // 标记消息为已读
  const markAsRead = (messageId) => {
    const message = messages.value.find(msg => msg.id === messageId)
    if (message && !message.isRead) {
      message.isRead = true
      saveToLocal()
      updateBadge()
    }
  }
  
  // 标记所有消息为已读
  const markAllAsRead = () => {
    messages.value.forEach(msg => {
      msg.isRead = true
    })
    saveToLocal()
    updateBadge()
  }
  
  // 删除消息
  const deleteMessage = (messageId) => {
    const index = messages.value.findIndex(msg => msg.id === messageId)
    if (index >= 0) {
      messages.value.splice(index, 1)
      saveToLocal()
      updateBadge()
    }
  }
  
  // 获取消息详情
  const getMessageById = (messageId) => {
    return messages.value.find(msg => msg.id === messageId)
  }
  
  // 设置当前消息
  const setCurrentMessage = (messageId) => {
    currentMessage.value = getMessageById(messageId)
    if (currentMessage.value) {
      markAsRead(messageId)
    }
  }
  
  // 清空所有消息
  const clearAllMessages = () => {
    messages.value = []
    currentMessage.value = null
    saveToLocal()
    updateBadge()
  }
  
  // 保存到本地存储
  const saveToLocal = () => {
    try {
      localStorage.setItem('messages', JSON.stringify(messages.value))
    } catch (error) {
      console.error('保存消息到本地存储失败:', error)
    }
  }
  
  // 从本地存储加载
  const loadFromLocal = () => {
    try {
      const stored = localStorage.getItem('messages')
      if (stored) {
        messages.value = JSON.parse(stored)
      }
    } catch (error) {
      console.error('从本地存储加载消息失败:', error)
      messages.value = []
    }
  }
  
  // 更新角标
  const updateBadge = () => {
    if (window.electronAPI) {
      window.electronAPI.setBadgeCount(unreadCount.value)
    }
  }
  
  // 初始化模拟数据
  const initMockData = () => {
    const mockMessages = [
      {
        id: '1',
        title: '系统维护通知',
        content: '系统将于今晚22:00-24:00进行维护，期间可能影响正常使用，请提前做好准备。维护内容包括：数据库优化、安全补丁更新、性能提升等。',
        summary: '系统将于今晚22:00-24:00进行维护，期间可能影响正常使用...',
        source: '系统管理员',
        timestamp: new Date(Date.now() - 1000 * 60 * 30).toISOString(),
        isRead: false
      },
      {
        id: '2',
        title: '新功能上线',
        content: '我们很高兴地宣布，消息推送功能已正式上线！现在您可以实时接收重要通知，不再错过任何重要信息。',
        summary: '我们很高兴地宣布，消息推送功能已正式上线！',
        source: '产品团队',
        timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2).toISOString(),
        isRead: true
      },
      {
        id: '3',
        title: '安全提醒',
        content: '请注意保护您的账户安全，不要将密码告诉他人，定期更换密码，启用双因素认证。',
        summary: '请注意保护您的账户安全，不要将密码告诉他人...',
        source: '安全中心',
        timestamp: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(),
        isRead: true
      }
    ]
    
    // 只在没有本地数据时添加模拟数据
    if (messages.value.length === 0) {
      messages.value = mockMessages
      saveToLocal()
    }
  }
  
  // 初始化
  const init = () => {
    loadFromLocal()
    initMockData()
    updateBadge()
  }
  
  return {
    messages,
    currentMessage,
    unreadCount,
    sortedMessages,
    addMessage,
    markAsRead,
    markAllAsRead,
    deleteMessage,
    getMessageById,
    setCurrentMessage,
    clearAllMessages,
    init
  }
})